
#include "app_includes.h"

void task_cdc(void *para)
{
    uint16_t data_len;
    uint32_t timeout;
    uint8_t send_zero_packet = 0;
    uint16_t ov_cnt = 0;
    while(1)
    {
        /* get usb vcp receive data */
        data_len = usb_vcp_get_rxdata(&board.cdc.usb_core_dev, board.cdc.usb_buffer);

        /* send data to hardware usart */
        if(data_len > 0)
        {
            board_serial_send(0, board.cdc.usb_buffer, data_len);
        }

        /* if hardware usart received data,usb send data to host */
        //board.cdc.usart_rx_data_len = usart_receive_data();
        board.cdc.usart_rx_data_len = ring_buffer_get_length(&board.serial[0].rx_ring_buff);
        if(board.cdc.usart_rx_data_len || send_zero_packet == 1)
        {
          if(board.cdc.usart_rx_data_len > 0)
            send_zero_packet = 1;
          else if(board.cdc.usart_rx_data_len == 0)
            send_zero_packet = 0;

          timeout = 50000;

          if((board.serial[0].rx_ring_buff.head + board.cdc.usart_rx_data_len) < board.serial[0].rx_ring_buff.size)
          {
            do
            {
              /* send data to host */
              if(usb_vcp_send_data(&board.cdc.usb_core_dev, &board.serial[0].rx_ring_buff.buff[board.serial[0].rx_ring_buff.head], board.cdc.usart_rx_data_len) == SUCCESS)
              {
                board.serial[0].rx_ring_buff.head += board.cdc.usart_rx_data_len;
                break;
              }
            }while(timeout --);

          }
          /* process the fifo overflow */
          else
          {
            do
            {
              /* send data to host */
              if(usb_vcp_send_data(&board.cdc.usb_core_dev, 
                  &board.serial[0].rx_ring_buff.buff[board.serial[0].rx_ring_buff.head], 
                  board.serial[0].rx_ring_buff.size - board.serial[0].rx_ring_buff.head) == SUCCESS)
              {
                /* get fifo overflow data count */
                ov_cnt = board.cdc.usart_rx_data_len - (board.serial[0].rx_ring_buff.size - board.serial[0].rx_ring_buff.head);
                board.serial[0].rx_ring_buff.head = 0;
                break;
              }
            }while(timeout --);
            timeout = 50000;
            do
            {
              /* send data to host */
              if(usb_vcp_send_data(&board.cdc.usb_core_dev, 
                  &board.serial[0].rx_ring_buff.buff[board.serial[0].rx_ring_buff.head], ov_cnt) == SUCCESS)
              {
                board.serial[0].rx_ring_buff.head = ov_cnt;
                break;
              }
            }while(timeout --);
          }
        }
        
        vTaskDelay(pdMS_TO_TICKS(10));
      }
}
